package com.ssyt.ec.exam.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.ssyt.ec.common.AppServlet;
import com.ssyt.ec.common.Constant;
import com.ssyt.ec.common.CountPoints;
import com.ssyt.ec.common.util.DateUtil;
import com.ssyt.ec.common.util.FastjsonUtil;
import com.ssyt.ec.common.util.SysuserUtil;
import com.ssyt.ec.exam.entity.AnswerEntity;
import com.ssyt.ec.exam.entity.PaperEntity;
import com.ssyt.ec.exam.service.ExamPlanService;
import com.ssyt.ec.exam.service.PaperService;
import com.ssyt.ec.que.entity.QuestionEntity;

@WebServlet("/exam/PaperServlet")
public class PaperServlet extends AppServlet {
	private static final long serialVersionUID = 1L;
	private PaperService paperService = new PaperService();
	private ExamPlanService examPlanService = new ExamPlanService();

	public PaperServlet() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String command = request.getParameter("command");
		if ("autoCreatePaper".equals(command)) {
			autoCreatePaper(request, response);
		} else if ("getPaper".equals(command)) {
			getPaper(request, response);
		} else if ("getPoints".equals(command)) {
			getPoints(request, response);
		}
	}

	/**
	 * 考试算分
	 * 
	 * @param request
	 * @param response
	 */
	private void getPoints(HttpServletRequest request,
			HttpServletResponse response) {
		int passPoint = Integer.parseInt(request.getParameter("passPoint"));
		int questionNumber = Integer.parseInt(request
				.getParameter("questionNumber"));
		// 考生答案Map
		Map<Integer, String> answerMap = new HashMap<>();
		// 循环获取考生答案
		for (int i = 0; i < questionNumber; i++) {
			String[] answer = request.getParameterValues("question" + i);
			Integer questionId = Integer.parseInt(request
					.getParameter("questionId" + i));
			answerMap.put(questionId, StringUtils.join(answer));
		}
		// 存入最终Map
		int studentId = SysuserUtil.getUserId(request);
		int examPlanId = (int) request.getSession().getAttribute("examPlanId");

		Map<Integer, Map<Integer, String>> studentMap = new HashMap<>();
		studentMap.put(studentId, answerMap);
		CountPoints.studentAnswerMap.put(examPlanId, studentMap);
		// 判断并获取分数
		int scores = CountPoints.getScores(examPlanId, studentId);
		print(response, scores);
		// 添加考试记录
		int isPass = 3;
		if (scores < passPoint) {
			isPass = 2;
		} else {
			isPass = 1;
		}

		List<Object> paramList = new ArrayList<>();
		paramList.add(studentId);
		paramList.add(examPlanId);
		paramList.add(scores);
		paramList.add(request.getSession().getAttribute("startTime"));
		paramList.add(isPass);
		paperService.addRecords(paramList);
	}

	/**
	 * 获取试卷
	 * 
	 * @param request
	 * @param response
	 */
	private void getPaper(HttpServletRequest request,
			HttpServletResponse response) {
		int examPlanId = Integer.parseInt(request.getParameter("examPlanId"));
		request.getSession().setAttribute("examPlanId", examPlanId);
		request.getSession().setAttribute("startTime", new Date());
		// 存入试题答案
		List<AnswerEntity> answerList = new ArrayList<>();
		String paperUrl = examPlanService.getPaperUrl(examPlanId);
		// 从本地获取json文件
		String json = FastjsonUtil.readJson(paperUrl);
		String string = JSON.parseObject(json).getString("questionList");
		List<QuestionEntity> list = JSON.parseArray(string,
				QuestionEntity.class);
		for (QuestionEntity QuestionEntity : list) {
			AnswerEntity answer = new AnswerEntity();
			answer.setId(QuestionEntity.getId());
			answer.setAnswer(QuestionEntity.getAnswer());
			answer.setScore(QuestionEntity.getScore());
			answerList.add(answer);
		}
		CountPoints.answerMap.put((int) examPlanId, answerList);
		print(response, JSON.parseObject(json));
	}

	/**
	 * 自动生成试卷
	 * 
	 * @param request
	 * @param response
	 */
	private void autoCreatePaper(HttpServletRequest request,
			HttpServletResponse response) {
		int operateUserId = SysuserUtil.getUserId(request);
		List<Object> paramList = new ArrayList<>();
		paramList.add(Constant.DEFAULT_PAPER_NAME);
		paramList.add(Constant.PAPER_URL + Constant.DEFAULT_PAPER_NAME
				+ DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".json");
		paramList.add(Constant.DEFAULT_PAPER_TYPE);
		paramList.add(Constant.DEFAULT_COURSE_ID);
		paramList.add(Constant.DEFAULT_TOTAL_POINT);
		paramList.add(Constant.DEFAULT_PASS_POINT);
		paramList.add(Constant.DEFAULT_TOTAL_MINUTES);
		paramList.add(Constant.DEFAULT_SINGLE_OPTION_NUMBER);
		paramList.add(Constant.DEFAULT_SINGLE_OPTION_EACH_POINT);
		paramList.add(Constant.DEFAULT_SINGLE_OPTION_DIFFICULTY);
		paramList.add(Constant.DEFAULT_MULTI_OPTION_NUMBER);
		paramList.add(Constant.DEFAULT_MULTI_OPTION_EACH_POINT);
		paramList.add(Constant.DEFAULT_MULTI_OPTION_DIFFICULTY);
		paramList.add(Constant.DEFAULT_JUDGE_NUMBER);
		paramList.add(Constant.DEFAULT_JUDGE_EACH_POINT);
		paramList.add(Constant.DEFAULT_JUDGE_DIFFICULTY);
		paramList.add(operateUserId);
		paramList.add(1);
		paramList.add("");
		long paperId = paperService.add(paramList);
		PaperEntity paper = paperService.getPaperList(paperId);
		if (paperId != 0) {
			List<QuestionEntity> queList = new ArrayList<>();
			List<QuestionEntity> singleList = paperService.getSingleOption();
			List<QuestionEntity> multiList = paperService.getMultiOption();
			List<QuestionEntity> judgeList = paperService.getJudge();
			for (QuestionEntity single : singleList) {
				single.setScore(Constant.DEFAULT_SINGLE_OPTION_EACH_POINT);
				queList.add(single);
			}
			for (QuestionEntity multi : multiList) {
				multi.setScore(Constant.DEFAULT_MULTI_OPTION_EACH_POINT);
				queList.add(multi);
			}
			for (QuestionEntity judge : judgeList) {
				judge.setScore(Constant.DEFAULT_JUDGE_EACH_POINT);
				queList.add(judge);
			}
			paper.setQuestionList(queList);
			FastjsonUtil.writeJson(paper.getPaperUrl(), FastjsonUtil
					.toJsonWithDateFormat(paper, "yyyy-MM-dd HH:mm:ss"));
			print(response, 1);
		}

	}
}
